import React, { useCallback, useEffect, useState, useRef, useMemo } from "react";
import { message } from "antd";
import {
	batchModifyOnlineInventory,
	batchModifyShopSkuCode,
	uploadSkuCodeToShop,
	enableSkuSynchronizedInventory,
	enableSpuSynchronizedInventory,
	batchSkuSynchronizedInventoryByHand,
	batchSpuSynchronizedInventoryByHand,
	changeGoodsSkuCodeSaleStatus,
	changeGoodsSpuCodeSaleStatus,
	getInventorySyncGetSchedule,
	manuallySynchronizeStoreProducts,
	goodsShopSkuMatchSysSku
} from "./service";
import moment from "moment";
import { useNavigate } from "react-router-dom";
export default fn => {
	const navigate = useNavigate();
	const [visibleDialogName, setVisibleDialogName] = useState("");
	const [customDialogProps, setCustomDialogProps] = useState({});

	const updateVisibleDialog = n => {
		setVisibleDialogName("");
		setTimeout(() => {
			setVisibleDialogName(n);
		}, 10);
	};
	const clearDialog = () => {
		updateVisibleDialog("");
		setCustomDialogProps({});
	};

	const refresh = d => {
		setTimeout(() => {
			fn.current && fn.current(d);
		}, 500);
	};
	const handleCommand = (TEXT, data, callback, query) => {
		console.log("command", TEXT, data);

		switch (TEXT) {
			case "刷新":
				callback && callback();
				break;
			case "手动同步商品":
				manuallySynchronizeStoreProducts({})
					.then(res => {
						const { success, data, msg } = res;
						if (success) {
							message.success(msg || "操作完成");
						} else {
							message.warning("操作失败");
						}
						if (res.success) refresh();
					})
					.catch(err => {
						console.log(err);
					})
					.finally(() => {});

				break;
			case "批量修改库存":
				{
					setCustomDialogProps({});
					updateVisibleDialog("ActionBatchEditInventoryModal");
				}
				break;
			case "批量修改库存确定后":
				{
					const { ids, stockNum } = data;
					batchModifyOnlineInventory({
						ids,
						stockNum
					})
						.then(res => {
							callback && callback(res);
							if (res.success) {
								let timer = setTimeout(() => {
									refresh();
									clearTimeout(timer);
									timer = null;
								}, 3000);
							}
						})
						.catch(err => {
							console.log(err);
							callback && callback(err);
						})
						.finally(() => {});
				}
				break;
			case "编辑库存":
				{
					setCustomDialogProps({ selectedRow: data });
					updateVisibleDialog("ActionEditInventoryModal");
				}
				break;
			case "编辑库存确定后":
				{
					const { ids, stockNum } = data;
					batchModifyOnlineInventory({
						ids,
						stockNum
					})
						.then(res => {
							callback && callback(res);
							if (res.success) refresh();
						})
						.catch(err => {
							console.log(err);
							callback && callback(err);
						})
						.finally(() => {});
				}
				break;
			case "批量编辑商品编码":
				{
					setCustomDialogProps();
					updateVisibleDialog("ActionEditSkuCodeModal");
				}
				break;
            case "自动生成设置":
                {
					setCustomDialogProps({});
					updateVisibleDialog("EncodeSettingModal");
				}
				break;
			case "批量编辑商品编码确定后":
				{
					const API_DATA = data
						.map(e => {
							return {
								id: e.id,
								skuOriginalCode: e.skuOriginalCode2,
								spuCode: e.spuCode2 || e.spuCode,
							};
						})
						.filter(e => e.id && (e.skuOriginalCode || e.spuCode));
					batchModifyShopSkuCode(API_DATA)
						.then(res => {
							console.log(res);
							callback && callback(res);
							if (res.success) refresh();
						})
						.catch(err => {
							console.log(err);
							callback && callback({ success: false, data: { total: "--", success: "--", failed: "--" } });
						})
						.finally(() => {});
				}
				break;
			case "上传商品编码":
				{
					setCustomDialogProps({});
					updateVisibleDialog("ActionUploadSkuToShopModal");
				}
				break;
			case "上传商品编码确定后":
				{
					const API_DATA = data.map(e => e.id).filter(e => e);
					console.log("上传商品编码", data, API_DATA);
					uploadSkuCodeToShop(API_DATA)
						.then(res => {
							console.log(res);
							callback && callback(res);
						})
						.catch(err => {
							console.log(err);
							callback && callback({ success: false, data: { total: "--", success: "--", failed: "--" } });
						})
						.finally(() => {});
				}
				break;
			case "开启同步库存":
				{
					setCustomDialogProps({});
					updateVisibleDialog("ActionEnableSynchronizedInventoryModal");
				}
				break;
			case "禁止同步库存":
				{
					setCustomDialogProps({});
					updateVisibleDialog("ActionDisableSynchronizedInventoryModal");
				}
				break;
			case "跳转SKU列表，按query刷新列表":
				refresh({ ...data, isSkuType: true });
				break;
			case "开启同步库存确认后":
			case "禁止同步库存确认后":
				{
					const { params, isSkuType } = data;
					const api = isSkuType ? enableSkuSynchronizedInventory : enableSpuSynchronizedInventory;
					api(params)
						.then(res => {
							const { success, data, msg } = res;
							const { spuCount, skuCount, successCount, failCount, failSkuCodes } = data;
							if (success) {
								if (isSkuType) {
									message.success(`操作完成，更新${successCount}条数据`);
								}
								// const { spuCount, skuCount, successCount, failCount, failSkuCodes } = data;
								callback && callback(res);
								refresh();
							} else {
								message.warning("提交失败");
							}
						})
						.catch(err => {
							console.log(err);
						})
						.finally(() => {});
				}

				break;
			case "手动同步库存":
				{
					setCustomDialogProps({});
					updateVisibleDialog("ActionManuallySynchronizingInventoryModal");
				}
				break;
			case "手动同步库存确认后":
				{
					const { params, isSkuType } = data;
					const api = isSkuType ? batchSkuSynchronizedInventoryByHand : batchSpuSynchronizedInventoryByHand;
					api(params)
						.then(res => {
							console.log(res);
							callback && callback(res);
						})
						.catch(err => {
							console.log(err);
							callback && callback({ success: false, data: { total: "--", success: "--", failed: "--" } });
						})
						.finally(() => {});
				}
				break;
			case "spu批量上架":
			case "spu批量下架":
			case "sku批量上架":
			case "sku批量下架":
			case "spu单列上架":
			case "spu单列下架":
				{
					const { params, isSkuType } = data;
					const api = TEXT.includes("spu") ? changeGoodsSpuCodeSaleStatus : changeGoodsSkuCodeSaleStatus;
					api(params)
						.then(res => {
							// TODO:  操作完成，更新0条数据
							// TODO: 检测到以下 1 个商品在平台后台已删除，已无法正常同步商品信息，是否从系统店铺商品资料中删除？
							console.log(res);
							if (res.success) {
								const { deleteList, successQty } = res.data;
								message.success(`操作完成，更新${successQty}条数据`);
								if (deleteList && deleteList.length) {
									EditActionsRef.current.setDialog("ActionConfirmDeleteShopSkuModal", {
										data: deleteList
									});
									// 检测到以下 1 个商品在平台后台已删除，已无法正常同步商品信息，是否从系统店铺商品资料中删除？
								}
							} else {
								message.warning(res.msg || "操作失败");
							}

							if (res.success) refresh();
						})
						.catch(err => {
							console.log(err);
						})
						.finally(() => {});
				}
				break;

			case "Excel导入":
				setCustomDialogProps(data); // {createTaskData,dataSource}
				updateVisibleDialog("ActionExcelImportProductsModal");
				break;
			case "线上导入":
				setCustomDialogProps({});
				updateVisibleDialog("ActionOnlineImportGoodsModal");
				break;
			case "线上导入确定后":
				manuallySynchronizeStoreProducts(data)
					.then(res => {
						callback(res);
					})
					.catch(err => {
						console.log(err);
					})
					.finally(() => {});

				break;

			case "导出所选店铺商品资料":

			case "导出筛选后的商品资料":

			case "导出已勾选的商品资料":
				setCustomDialogProps({ createTaskData: data });
				updateVisibleDialog("ActionExportExcelModal");
				break;
			case "匹配":
				navigate("/views/goods/system?skuCode=" + data.skuCode);

			case "已勾选的未绑定商品":
			case "已筛选的未绑定商品":
				setCustomDialogProps({ goodsData: data, type: TEXT, query });
				updateVisibleDialog("ActionCreateSysGoodsModal");
				break;
			case "生成系统商品结果":
				setCustomDialogProps({ goodsResultData: data });
				updateVisibleDialog("ActionCreateSysGoodsResultModal");
				break;
			// const API_DATA = { id: data.id };
			// goodsShopSkuMatchSysSku(API_DATA)
			// 	.then(({ success, msg }) => {
			// 		if (success) {
			// 			message.success(msg || "操作成功");
			// 		} else {
			// 			message.warning(msg || "操作失败");
			// 		}
			// 	})
			// 	.catch(err => {
			// 		console.error(err);
			// 		message.warning("操作失败");
			// 	})
			// 	.finally(() => {});

			default:
				break;
		}
	};

	return {
		handleCommand,
		clearDialog,
		visibleDialogName,
		setVisibleDialogName: updateVisibleDialog,
		customDialogProps,
		setCustomDialogProps
	};
};
